package com.qifan.energy.mvp.model;

import com.qifan.energy.mvp.callback.ICallBack;
import com.qifan.energy.mvp.callback.IHttpListener;
import com.qifan.energy.netWork.RetrofitManager;
import com.qifan.energy.util.GsonUtils;

import java.util.Map;

/**
 * @author : FangShiKang
 * @date : 2020/04/11.
 * email : fangshikang@outlook.com
 * desc :   Model层实现类
 */
public class IModelImplement implements IModel {

    /**
     * Get
     * @param url
     * @param clazz
     * @param callBack
     */
    @Override
    public void onGetData(String url, Class clazz, ICallBack callBack) {
        RetrofitManager.getInstance().retrofitGet(url, new IHttpListener() {
            @Override
            public void onSuccess(String data) {
                try {
                    Object o = GsonUtils.getGson().fromJson(data, clazz);
                    if (callBack != null) {
                        callBack.onSuccess(o);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    if (callBack != null) {
                        callBack.onFailed(e.getMessage());
                    }
                }
            }

            @Override
            public void onFailed(String error) {
                if (callBack != null) {
                    callBack.onFailed(error);
                }
            }
        });
    }

    /**
     * Post
     *
     * @param url
     * @param map
     * @param clazz
     * @param callBack
     */
    @Override
    public void onPostData(String url, Map<String, String> map, Class clazz, ICallBack callBack) {
        RetrofitManager.getInstance().retrofitPost(url, map, new IHttpListener() {
            @Override
            public void onSuccess(String data) {
                try {
                    Object o = GsonUtils.getGson().fromJson(data, clazz);
                    if (callBack != null) {
                        callBack.onSuccess(o);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    if (callBack != null) {
                        callBack.onFailed(e.getMessage());
                    }
                }
            }

            @Override
            public void onFailed(String error) {
                if (callBack != null) {
                    callBack.onFailed(error);
                }
            }
        });
    }
}
